package CH02链表结构.LeetCode链表;

public class LC61 {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        int size = 0;
        ListNode p = head;
        ListNode rear = null;
        while (true) {
            size++;
            if (p.next == null) {
                rear = p;
                break;
            }
            p = p.next;
        }
        k = k % size;
        if (k == 0) {
            return head;
        }
        ListNode left = head;
        ListNode right = head;
        for (int i = 0; i < k; i++) {
            right = right.next;
        }
        if (right == null) {
            return head;
        }
        while (right.next != null) {
            right = right.next;
            left = left.next;
        }
        ListNode h = left.next;
        left.next = null;
        rear.next = head;
        return h;
    }
}